//vuex仓库入口
//引入Vue核心库
import Vue from "vue";
//引入Vuex
import Vuex from "vuex";
//应用Vuex插件
Vue.use(Vuex);

const setCartLocalStorge = (state) => {
  const { cart, allcount, allprice } = state;
  const cartListString = JSON.stringify(cart);
  const Allcount = JSON.stringify(allcount);
  const Allprice = JSON.stringify(allprice);

  localStorage.cart = cartListString;
  localStorage.allcount = Allcount;
  localStorage.allprice = Allprice;
};

const getCartLocalStorge = () => {
  if (localStorage.cart) return JSON.parse(localStorage.cart);
  return {};
};
const getAllcount = () => {
  if (localStorage.allcount) return JSON.parse(localStorage.allcount);
  return 0;
};
const getAllprice = () => {
  if (localStorage.allcprice) return JSON.parse(localStorage.allcprice);
  return 0;
};

//准备actions对象——响应组件中用户的动作
const actions = {};
//准备mutations对象——修改state中的数据
const mutations = {
  CLEAR(state){
    state = {
      allprice:0,
      allcount:0,
      cart:{}
    }
    setCartLocalStorge(state);
  },
  MINUS(state, val) {
    const { shopId, productId, product } = val;
    if (!state.cart[shopId][productId]) return;
    if (state.cart[shopId][productId].count == 0) return;
    let shopInfo = state.cart[shopId];
    let productInfo = shopInfo[productId];
    productInfo.count -= 1;
    shopInfo[productId] = productInfo;
    state.cart[shopId] = shopInfo;
    state.allcount -= 1;
    state.allprice -= product.price;
    if (productInfo.count == 0) delete state.cart[shopId];

    if (state.allprice < 0) state.allprice = 0;
    if (state.allcount < 0) state.allcount = 0;

    setCartLocalStorge(state);
  },
  PLUS(state, val) {
    const { shopId, productId, product } = val;
    // console.log(shopId,productId,product)
    let shopInfo = state.cart[shopId];
    if (!shopInfo) {
      shopInfo = {};
    }
    let productInfo = shopInfo[productId];
    if (!productInfo) {
      productInfo = product;
      productInfo.count = 0;
    }
    productInfo.count += 1;
    shopInfo[productId] = productInfo;
    state.cart[shopId] = shopInfo;
    state.allcount += 1;
    state.allprice += product.price;
    setCartLocalStorge(state);
  },
  CLEARALL(state, val) {
    state.allcount = 0;
    state.allprice = 0;
    state.cart[val] = {};
    setCartLocalStorge(state);
  },
};
//准备state对象——保存具体的数据
const state = {
  allcount: getAllcount(),
  allprice: getAllprice(),
  cart: getCartLocalStorge(),
};

//创建并暴露store
export default new Vuex.Store({
  actions,
  mutations,
  state,
});
